package com.maila.xiaoaoschool.activity;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.util.SparseIntArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AccelerateInterpolator;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.view.animation.AnimationSet;
import android.view.animation.LinearInterpolator;
import android.view.animation.TranslateAnimation;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.flipboard.bottomsheet.BottomSheetLayout;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.maila.xiaoaoschool.R;
import com.maila.xiaoaoschool.adapter.CommentAdapter;
import com.maila.xiaoaoschool.adapter.GoodsAdapter;
import com.maila.xiaoaoschool.adapter.SelectAdapter;
import com.maila.xiaoaoschool.adapter.TypeAdapter;
import com.maila.xiaoaoschool.api.ShopApi;
import com.maila.xiaoaoschool.entity.ShopClasses;
import com.maila.xiaoaoschool.entity.ShopComment;
import com.maila.xiaoaoschool.net.VolleyInterface;
import com.maila.xiaoaoschool.util.StartActivityUtils;
import com.maila.xiaoaoschool.widget.DividerDecoration;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;

import java.io.Serializable;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import se.emilsjolander.stickylistheaders.StickyListHeadersListView;

/**
 * Created by mark on 2018/3/1.
 */

public class ShopActivity extends AppCompatActivity  {
    @BindView(R.id.white_return_iv)
    AutoRelativeLayout whiteReturnIv;
    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.tv_good)
    TextView tvGood;
    @BindView(R.id.v_good)
    View vGood;
    @BindView(R.id.rl_good)
    AutoRelativeLayout rlGood;
    @BindView(R.id.tv_comment)
    TextView tvComment;
    @BindView(R.id.v_comment)
    View vComment;
    @BindView(R.id.rl_comment)
    AutoRelativeLayout rlComment;
    @BindView(R.id.tv_shopinfo)
    TextView tvShopinfo;
    @BindView(R.id.v_shopinfo)
    View vShopinfo;
    @BindView(R.id.rl_shopinfo)
    AutoRelativeLayout rlShopinfo;
    @BindView(R.id.ll_menu)
    AutoLinearLayout llMenu;
    @BindView(R.id.ll_title)
    AutoLinearLayout llTitle;
    @BindView(R.id.lv_comment)
    ListView lvComment;
    @BindView(R.id.tv_shop_address)
    TextView tvShopAddress;
    @BindView(R.id.iv_location)
    ImageView ivLocation;
    @BindView(R.id.ll_location)
    AutoRelativeLayout llLocation;
    @BindView(R.id.tv_shop_phone)
    TextView tvShopPhone;
    @BindView(R.id.ll_change_phone)
    AutoRelativeLayout llChangePhone;
    @BindView(R.id.tv_business_time)
    TextView tvBusinessTime;
    @BindView(R.id.tv_shop_notice)
    TextView tvShopNotice;
    @BindView(R.id.tv_manjian)
    TextView tvManjian;
    @BindView(R.id.ll_manjian)
    AutoLinearLayout llManjian;
    @BindView(R.id.tv_shoudan)
    TextView tvShoudan;
    @BindView(R.id.ll_shoudan)
    AutoLinearLayout llShoudan;
    @BindView(R.id.tv_zhekou)
    TextView tvZhekou;
    @BindView(R.id.ll_zhekou)
    AutoLinearLayout llZhekou;
    @BindView(R.id.tv_tejia)
    TextView tvTejia;
    @BindView(R.id.ll_tejia)
    AutoLinearLayout llTejia;
    @BindView(R.id.tv_fanquan)
    TextView tvFanquan;
    @BindView(R.id.ll_fanquan)
    AutoLinearLayout llFanquan;
    @BindView(R.id.ll_shopinfo)
    AutoLinearLayout llShopinfo;
    @BindView(R.id.tv_message)
    TextView tvMessage;
    @BindView(R.id.ll_gonggao)
    AutoLinearLayout llGonggao;
    @BindView(R.id.typeRecyclerView)
    RecyclerView typeRecyclerView;
    @BindView(R.id.itemListView)
    StickyListHeadersListView itemListView;
    @BindView(R.id.bottomSheetLayout)
    BottomSheetLayout bottomSheetLayout;
    @BindView(R.id.imgCart)
    ImageView imgCart;
    @BindView(R.id.tvCount)
    TextView tvCount;
    @BindView(R.id.tvCost)
    TextView tvCost;
    @BindView(R.id.tvTips)
    TextView tvTips;
    @BindView(R.id.tvSubmit)
    TextView tvSubmit;
    @BindView(R.id.bottom)
    LinearLayout bottom;
    @BindView(R.id.containerLayout)
    RelativeLayout containerLayout;
    @BindView(R.id.ll_shop_details)
    AutoRelativeLayout llShopDetails;
    @BindView(R.id.rel_layout)
    AutoRelativeLayout relLayout;
    @BindView(R.id.tv_fee)
    TextView tvFee;
    private int showtype = 0;

    private ViewGroup anim_mask_layout;// 移动对象
    private Handler mHanlder;
    private View bottomSheet;
    private RecyclerView rvSelected;


    private List<ShopClasses.DataBean.GoodBean> dataList;
    private List<ShopClasses.DataBean> typeList;
    private SparseArray<ShopClasses.DataBean.GoodBean> selectedList;
    private List<ShopClasses.DataBean.GoodBean> selecteddata=new ArrayList<>();
    private SparseIntArray groupSelect;

    private GoodsAdapter myAdapter;
    private SelectAdapter selectAdapter;
    private TypeAdapter typeAdapter;

    private NumberFormat nf;

    int c_page = 1;
    int c_size = 30;
    CommentAdapter commentAdapter;
    String shopID = "";
    Gson gson = new Gson();
    String shopName = "";
    private String transfee = "";
    private double limitfee=14.99;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shop);
        ButterKnife.bind(this);

        nf = NumberFormat.getCurrencyInstance();
        nf.setMaximumFractionDigits(2);
        mHanlder = new Handler(getMainLooper());
        dataList = new ArrayList<>();
        typeList = new ArrayList<>();
        selectedList = new SparseArray<>();
        groupSelect = new SparseIntArray();
        shopID = getIntent().getStringExtra("ID");
        shopName = getIntent().getStringExtra("shop_name");
        transfee = getIntent().getStringExtra("fee");
        tvShopName.setText(shopName);
        tvFee.setText("配送费： ￥" + transfee);
        initview();
        initdata();
    }

    private void initdata() {

        getlistData();

    }

    private void getcommentdata() {
        new ShopApi(this, new VolleyInterface() {
            @Override
            public void onSuccess(String result) {
                ShopComment shopComment = gson.fromJson(result, ShopComment.class);
                if (shopComment.getResult() == 1) {
                    if (c_page == 1) {
                        commentAdapter.setMdata(shopComment.getData());
                    } else {
                        commentAdapter.addMdata(shopComment.getData());
                    }

                } else {

                }
            }

            @Override
            public void onError(VolleyError error) {

            }
        }).getShopCpmments(shopID, c_page, c_size);
    }

    public void getlistData() {

        new ShopApi(this, new VolleyInterface() {
            @Override
            public void onSuccess(String result) {
                try {
                    ShopClasses shopClasses = gson.fromJson(result, ShopClasses.class);
                    if (shopClasses.getResult() == 1) {
                        if (shopClasses.getData() != null) {
                            typeList=shopClasses.getData();
                            for(int i=0;i<typeList.size();i++){
                                List<ShopClasses.DataBean.GoodBean> datas=SetType(typeList,i);
                                dataList.addAll(datas);
                            }
                            typeAdapter.setDataList(typeList);
                            myAdapter.setDataList(dataList);
                            itemListView.setOnScrollListener(new AbsListView.OnScrollListener() {
                                @Override
                                public void onScrollStateChanged(AbsListView view, int scrollState) {

                                }

                                @Override
                                public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                                    ShopClasses.DataBean.GoodBean item = dataList.get(firstVisibleItem);
                                    if(typeAdapter.selectTypeId == item.getType()) {
//                                        typeAdapter.selectTypeId = item.getType();
                                        typeAdapter.setIndex(getSelectedPosition(item.getType()));
                                        typeAdapter.notifyDataSetChanged();
                                        typeRecyclerView.smoothScrollToPosition(getSelectedGroupPosition(item.getType()));
                                    }
                                }
                            });
                        }

                    }
                } catch (JsonSyntaxException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(VolleyError error) {

            }
        }).getShopClasses(shopID);

    }

    private List<ShopClasses.DataBean.GoodBean> SetType(List<ShopClasses.DataBean> typeList, int i) {
        int typeid=typeList.get(i).getTypeid();
        String typename=typeList.get(i).getTypename();
        List<ShopClasses.DataBean.GoodBean> datas=typeList.get(i).getGood();
        for(int j=0;j<datas.size();j++){
            datas.get(j).setType(typeid);
            datas.get(j).setTypename(typename);
        }
        return datas;
    }

    private void initview() {
        anim_mask_layout = (RelativeLayout) findViewById(R.id.containerLayout);

        commentAdapter=new CommentAdapter(this);
        lvComment.setAdapter(commentAdapter);

        typeRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        typeAdapter = new TypeAdapter(this,typeList);
        typeRecyclerView.setAdapter(typeAdapter);
        typeRecyclerView.addItemDecoration(new DividerDecoration(this));

        myAdapter = new GoodsAdapter(dataList,this);
        itemListView.setAdapter(myAdapter);


    }

    @OnClick({R.id.white_return_iv, R.id.rl_good, R.id.rl_comment, R.id.rl_shopinfo, R.id.ll_location, R.id.ll_change_phone, R.id.bottom, R.id.tvSubmit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.white_return_iv:
                finish();
                break;
            case R.id.rl_good:
                showtype = 0;
                setmenustatus();
                break;
            case R.id.rl_comment:
                showtype = 1;
                setmenustatus();
                getcommentdata();
                break;
            case R.id.rl_shopinfo:
                showtype = 2;
                setmenustatus();
                break;
            case R.id.ll_location:
                break;
            case R.id.ll_change_phone:
                break;
            case R.id.bottom:
                showBottomSheet();
                break;
            case R.id.tvSubmit:
                selecteddata.clear();
              for(int i=0;i<selectedList.size();i++){
                  selecteddata.add(selectedList.get(selectedList.keyAt(i)));
              }
                Intent intent = new Intent(this, AffirmOrderActivity.class);
                intent.putExtra("OPT", 1);
                intent.putExtra("shopname", shopName);
                intent.putExtra("transfee", transfee);
                intent.putExtra("shopID", shopID);
                intent.putExtra("data", (Serializable) selecteddata);
                startActivity(intent);

                break;
        }
    }

    /**
     * 弹出购物车
     */
    private void showBottomSheet() {
        if(bottomSheet==null){
            bottomSheet = createBottomSheetView();
        }
        if(bottomSheetLayout.isSheetShowing()){
            bottomSheetLayout.dismissSheet();
        }else {
            if(selectedList.size()!=0){
                bottomSheetLayout.showWithSheetView(bottomSheet);
            }
        }
    }

    private View createBottomSheetView() {
        View view = LayoutInflater.from(this).inflate(R.layout.layout_bottom_sheet,(ViewGroup) getWindow().getDecorView(),false);
        rvSelected = (RecyclerView) view.findViewById(R.id.selectRecyclerView);
        rvSelected.setLayoutManager(new LinearLayoutManager(this));
        TextView clear = (TextView) view.findViewById(R.id.clear);
        clear.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                clearCart();
            }
        });
        selectAdapter = new SelectAdapter(this,selectedList);
        rvSelected.setAdapter(selectAdapter);
        return view;
    }



    public void onTypeClicked(int typeId){
        itemListView.setSelection(getSelectedPosition(typeId));
    }

    private int getSelectedPosition(int typeId){
        int position = 0;
        for(int i=0;i<typeList.size();i++){
            if(typeList.get(i).getTypeid()== typeId){
                position = i;
                break;
            }
        }
        return position;
    }


    /**
     * 切换界面
     */
    private void setmenustatus() {

        if (showtype == 0) {
            tvComment.setTextColor(Color.parseColor("#666666"));
            vComment.setVisibility(View.GONE);
            vGood.setVisibility(View.VISIBLE);
            vShopinfo.setVisibility(View.GONE);
            tvGood.setTextColor(Color.parseColor("#f2673e"));
            tvShopinfo.setTextColor(Color.parseColor("#666666"));
            lvComment.setVisibility(View.GONE);
            llShopDetails.setVisibility(View.VISIBLE);
            llShopinfo.setVisibility(View.GONE);
        } else if (showtype == 1) {
            tvComment.setTextColor(Color.parseColor("#f2673e"));
            vComment.setVisibility(View.VISIBLE);
            vGood.setVisibility(View.GONE);
            vShopinfo.setVisibility(View.GONE);
            tvGood.setTextColor(Color.parseColor("#666666"));
            tvShopinfo.setTextColor(Color.parseColor("#666666"));
            lvComment.setVisibility(View.VISIBLE);
            llShopinfo.setVisibility(View.GONE);
            llShopDetails.setVisibility(View.GONE);
        } else {
            tvShopinfo.setTextColor(Color.parseColor("#f2673e"));
            tvGood.setTextColor(Color.parseColor("#666666"));
            tvComment.setTextColor(Color.parseColor("#666666"));
            vComment.setVisibility(View.GONE);
            vGood.setVisibility(View.GONE);
            vShopinfo.setVisibility(View.VISIBLE);
            llShopinfo.setVisibility(View.VISIBLE);
            lvComment.setVisibility(View.GONE);
            llShopDetails.setVisibility(View.GONE);
        }
    }



    //动画
    public void playAnimation(int[] start_location){
        ImageView img = new ImageView(this);
        img.setImageResource(R.mipmap.jia);
        setAnim(img,start_location);
    }

    private Animation createAnim(int startX, int startY){
        int[] des = new int[2];
        imgCart.getLocationInWindow(des);

        AnimationSet set = new AnimationSet(false);

        Animation translationX = new TranslateAnimation(0, des[0]-startX, 0, 0);
        translationX.setInterpolator(new LinearInterpolator());
        Animation translationY = new TranslateAnimation(0, 0, 0, des[1]-startY);
        translationY.setInterpolator(new AccelerateInterpolator());
        Animation alpha = new AlphaAnimation(1,0.5f);
        set.addAnimation(translationX);
        set.addAnimation(translationY);
        set.addAnimation(alpha);
        set.setDuration(500);

        return set;
    }

    private void addViewToAnimLayout(final ViewGroup vg, final View view,
                                     int[] location) {

        int x = location[0];
        int y = location[1];
        int[] loc = new int[2];
        vg.getLocationInWindow(loc);
        view.setX(x);
        view.setY(y-loc[1]);
        vg.addView(view);
    }
    private void setAnim(final View v, int[] start_location) {

        addViewToAnimLayout(anim_mask_layout, v, start_location);
        Animation set = createAnim(start_location[0],start_location[1]);
        set.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(final Animation animation) {
                mHanlder.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        anim_mask_layout.removeView(v);
                    }
                },100);
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        v.startAnimation(set);
    }



    //添加商品
    public void add(ShopClasses.DataBean.GoodBean item, boolean refreshGoodList){

        int groupCount = groupSelect.get(item.getType());
        if(groupCount==0){
            groupSelect.append(item.getType(),1);
        }else{
            groupSelect.append(item.getType(),++groupCount);
        }

        ShopClasses.DataBean.GoodBean temp = selectedList.get(item.getGoodsid());
        if(temp==null){

            item.setBuynum(1);
            selectedList.append(item.getGoodsid(),item);
        }else{
            temp.setBuynum(1+temp.getBuynum());
        }
        update(refreshGoodList);
    }
    //移除商品
    public void remove(ShopClasses.DataBean.GoodBean item, boolean refreshGoodList){

        int groupCount = groupSelect.get(item.getType());
        if(groupCount==1){
            groupSelect.delete(item.getType());
        }else if(groupCount>1){
            groupSelect.append(item.getType(),--groupCount);
        }

        ShopClasses.DataBean.GoodBean temp = selectedList.get(item.getGoodsid());
        if(temp!=null){
            if(temp.getBuynum()<2){
                selectedList.remove(item.getGoodsid());
            }else{
                item.setBuynum(item.getBuynum()-1);
            }
        }
        update(refreshGoodList);
    }
    //刷新布局 总价、购买数量等
    private void update(boolean refreshGoodList){
        int size = selectedList.size();
        int count =0;
        double cost = 0;
        for(int i=0;i<size;i++){
            ShopClasses.DataBean.GoodBean item = selectedList.valueAt(i);
            count += item.getBuynum();
            cost += item.getBuynum()*item.getCost();
        }

        if(count<1){
            tvCount.setVisibility(View.GONE);
        }else{
            tvCount.setVisibility(View.VISIBLE);
        }

        tvCount.setText(String.valueOf(count));

        if(cost > limitfee){
            tvTips.setVisibility(View.GONE);
            tvSubmit.setVisibility(View.VISIBLE);
        }else{
            tvSubmit.setVisibility(View.GONE);
            tvTips.setVisibility(View.VISIBLE);
        }

        tvCost.setText(nf.format(cost));

        if(myAdapter!=null && refreshGoodList){
            myAdapter.notifyDataSetChanged();
        }
        if(selectAdapter!=null){
            selectAdapter.notifyDataSetChanged();
        }
        if(typeAdapter!=null){
            typeAdapter.notifyDataSetChanged();
        }
        if(bottomSheetLayout.isSheetShowing() && selectedList.size()<1){
            bottomSheetLayout.dismissSheet();
        }
    }
    //清空购物车
    public void clearCart(){
        selectedList.clear();
        groupSelect.clear();
        update(true);

    }
    //根据商品id获取当前商品的采购数量
    public int getSelectedItemCountById(int id){
        ShopClasses.DataBean.GoodBean temp = selectedList.get(id);
        if(temp==null){
            return 0;
        }
        return temp.getBuynum();
    }
    //根据类别Id获取属于当前类别的数量
    public int getSelectedGroupCountByTypeId(int typeId){
        return groupSelect.get(typeId);
    }
    //根据类别id获取分类的Position 用于滚动左侧的类别列表
    public int getSelectedGroupPosition(int typeId){
        for(int i=0;i<typeList.size();i++){
            if(typeId==typeList.get(i).getTypeid()){
                return i;
            }
        }
        return 0;
    }


}
